﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using WarehouseManagement.Shared;
using WarehouseManagement.Shared.Settings;

namespace WarehouseManagement.Views.Shared
{
    public partial class BackupDataForm : DevExpress.XtraEditors.XtraForm
    {
        private DatabaseSettings _settings;

        public BackupDataForm()
        {
            InitializeComponent();
        }

        private void LoadSettings()
        {
            _settings = SettingsManager.ReadSettings(GlobalMemory.DatabaseSettingFilePath);
        }

        private void txtFolder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                FolderBrowserDialog dia = new FolderBrowserDialog();
                dia.RootFolder = Environment.SpecialFolder.MyComputer;
                dia.ShowNewFolderButton = true;
                if (dia.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                    return;
                txtFolder.Text = dia.SelectedPath;

            }
        }

        private void BackupDataForm_Load(object sender, EventArgs e)
        {
            AssignFileName();
        }

        private void AssignFileName()
        {
            LoadSettings();
            txtFileName.Text = string.Format("{0}-{1}.{2}.{3} {4}.{5}.{6}.bak",
                _settings.DatabaseName,
                DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDo_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFolder.Text))
            {
                XtraMessageBox.Show("Bạn chưa chọn nơi lưu file", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            AssignFileName();

            Backup bkpDBFull = new Backup();
            /* Specify whether you want to back up database or files or log */
            bkpDBFull.Action = BackupActionType.Database;
            /* Specify the name of the database to back up */
            bkpDBFull.Database = _settings.DatabaseName;
            /* You can take backup on several media type (disk or tape), here I am
             * using File type and storing backup on the file system */

            var fullPath = string.Format("{0}\\{1}", txtFolder.Text, txtFileName.Text);
            bkpDBFull.Devices.AddDevice(fullPath, DeviceType.File);
            bkpDBFull.BackupSetName = "Warehouse Management backup set";
            bkpDBFull.BackupSetDescription = "Warehouse Management database - Full Backup";
            /* You can specify the expiration date for your backup data
             * after that date backup data would not be relevant */
            bkpDBFull.ExpirationDate = DateTime.Today.AddYears(100);

            /* You can specify Initialize = false (default) to create a new 
             * backup set which will be appended as last backup set on the media. You
             * can specify Initialize = true to make the backup as first set on the
             * medium and to overwrite any other existing backup sets if the all the
             * backup sets have expired and specified backup set name matches with
             * the name on the medium */
            bkpDBFull.Initialize = false;

            /* Wiring up events for progress monitoring */
            bkpDBFull.PercentComplete += CompletionStatusInPercent;
            bkpDBFull.Complete += Backup_Completed;

            /* SqlBackup method starts to take back up
             * You can also use SqlBackupAsync method to perform the backup 
             * operation asynchronously */
            var myServer = GetServerInfo(_settings);
            bkpDBFull.SqlBackup(myServer);
        }

        private Server GetServerInfo(DatabaseSettings settings)
        {
            var conStr = settings.ConnectionString;
            var sqlConn = new SqlConnection(conStr);
            var sqlServer = new Server(new ServerConnection(sqlConn));
            return sqlServer;
        }


        private void CompletionStatusInPercent(object sender, PercentCompleteEventArgs args)
        {
            pgProgress.EditValue = args.Percent;

            Application.DoEvents();
        }
        private void Backup_Completed(object sender, ServerMessageEventArgs args)
        {
            XtraMessageBox.Show(string.Format("{0}", args.Error.Message), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
        //private void Restore_Completed(object sender, ServerMessageEventArgs args)
        //{
        //    XtraMessageBox.Show("Phục hồi dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //}

        private void pgProgress_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            e.DisplayText = string.Format("{0}%", e.Value);
            lblComplete.Text = e.DisplayText;
        }
    }
}